# -*- coding:utf-8 -*-
import os
import time
import urllib

import requests
import json

from datetime import datetime
from .jd_logger import logger
from .config import global_config
from selenium import webdriver
from selenium.common.exceptions import WebDriverException
import http.client

class Timer(object):
    def __init__(self, sleep_interval=0.5):
        # '2018-09-28 22:45:50.000'
        self.buy_time = datetime.strptime(global_config.getRaw('config','buy_time'), "%Y-%m-%d %H:%M:%S.%f")
        self.buy_time_ms = int(time.mktime(self.buy_time.timetuple()) * 1000.0 + self.buy_time.microsecond / 1000)
        self.sleep_interval = sleep_interval

        self.diff_time = self.local_jd_time_diff()

    def start_driver(self):
        try:
            driver = self.find_chromedriver()
        except WebDriverException:
            print("Unable to find chromedriver, Please check the drive path.")
        else:
            return driver

    def find_chromedriver(self):
        try:
            driver = webdriver.Chrome()

        except WebDriverException:
            chrome_path = os.path.abspath(os.path.join("/usr/src/drivers", "chromedriver"))
            try:
                driver = webdriver.Chrome(executable_path=chrome_path, chrome_options=self.build_chrome_options())

            except WebDriverException as e:
                print(e)
                print(chrome_path)
                raise
        return driver

    def build_chrome_options(self):
        """配置启动项"""
        chrome_options = webdriver.ChromeOptions()
        chrome_options.accept_untrusted_certs = True
        chrome_options.assume_untrusted_cert_issuer = True
        arguments = ['--no-sandbox', '--disable-impl-side-painting', '--disable-setuid-sandbox',
                     '--disable-seccomp-filter-sandbox',
                     '--disable-breakpad', '--disable-client-side-phishing-detection', '--disable-cast',
                     '--disable-cast-streaming-hw-encoding', '--disable-cloud-import', '--disable-popup-blocking',
                     '--ignore-certificate-errors', '--disable-session-crashed-bubble', '--disable-ipv6',
                     '--allow-http-screen-capture', '--start-maximized']
        for arg in arguments:
            chrome_options.add_argument(arg)
        # chrome_options.add_argument(f'--user-agent={choice(get_useragent_data())}')
        # 设置连接超时为 None，使用默认值
        chrome_options.add_argument('--connect-timeout=60')  # 设置连接超时，默认值为 60秒

        return chrome_options

    def jd_time(self):
        """
        从京东服务器获取时间戳
        """
        url = 'https://api.m.jd.com'
        headers = {
            'Accept': '*/*',
            'User-Agent': global_config.getRaw('config', 'DEFAULT_USER_AGENT'),
            'Accept-Encoding': 'gzip, deflate, br',
            'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,ar;q=0.7',
            'Referer': 'https://item.m.jd.com/',
            'Origin': 'https://item.m.jd.com'
        }
        payload = {
            "appid": 'yinliu',
            "functionId": 'yinliu_service_display',
            "loginType": '2',
            "_": str(self.local_time()),
            "cthr": '1',
            "body": '{"functionName":"CHECK_SHIELD","isNewVersion":"1","_format_":"json"}'
        }
        resp = requests.get(url, verify=False, params=payload, headers=headers)
        jd_timestamp = int(resp.headers.get('X-API-Request-Id')[-13:])
        return jd_timestamp

    def jd_time_conn(self):
        conn = http.client.HTTPSConnection("api.m.jd.com")
        payload = ''
        headers = {
            'Accept': '*/*',
            'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,ar;q=0.7',
            'User-Agent': '\'"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36"\'',
            'Referer': 'https://item.m.jd.com/',
            'Host': 'api.m.jd.com',
            'Connection': 'keep-alive'
        }
        conn.request("GET",
                     "/?appid=yinliu&functionId=yinliu_service_display&loginType=2&_="+str(self.local_time())+"&cthr=1&body=%257B%2522functionName%2522:%2522CHECK_SHIELD%2522,%2522isNewVersion%2522:%25221%2522,%2522_format_%2522:%2522json%2522%257D",
                     payload, headers)
        resp = conn.getresponse()
        # data = res.read()
        # print(data.decode("utf-8"))
        jd_timestamp = int(resp.headers.get('X-API-Request-Id')[-13:])
        return jd_timestamp

    def jd_time_selenium(self):
        # 使用Selenium打开京东网站
        self.driver = self.start_driver()
        self.driver.get('https://www.jd.com/')

        # 获取JS变量中的服务器时间
        server_time = self.driver.execute_script('return window.pageConfig.serverTime')
        # 关闭浏览器
        self.driver.quit()
        return server_time

    def local_time(self):
        """
        获取本地毫秒时间
        :return:
        """
        return int(round(time.time() * 1000))

    def local_jd_time_diff(self):
        """
        计算本地与京东服务器时间差
        :return:
        """
        return self.local_time() - self.jd_time_conn()

    def start(self):
        logger.info('正在等待到达设定时间:{}，检测本地时间与京东服务器时间误差为【{}】毫秒'.format(self.buy_time, self.diff_time))
        while True:
            # 本地时间减去与京东的时间差，能够将时间误差提升到0.1秒附近
            # 具体精度依赖获取京东服务器时间的网络时间损耗
            if self.local_time() - self.diff_time >= self.buy_time_ms:
                logger.info('时间到达，开始执行……')
                break
            else:
                time.sleep(self.sleep_interval)

    def buytime_get(self):
        pass
